package com.ly.demo.download;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

/**
 * @author liuyang
 * @des
 * @Version 1.0
 * @Date: 27/08/2021 09:23
 */
@Slf4j
public class Down {

    public static void main(String[] args) {
//        String host = "10.15.100.2";
//        int port = 22;
//        String username = "root";
//        String password = "rvCC744Hx%TEiZs0";
//        String remotePath = "/home";
//        String fileName = "1.jpg";
//        String absolutePath = "/home/1.jpg";
//        String localPath = "D://";
//
//        try {
//            downloadFile(host,port,username,password,absolutePath,localPath);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        windowDownload();
        //无密码
        getShareFile("smb://share:admin@192.168.10.124/share/test1.jpg", "D:/test");
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
        String fileName, String localPath) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            int reply;
            log.info("连接FTP服务器");
            ftpClient.connect(host, port);

            log.info("登录");
            ftpClient.login(username, password);

            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                log.info("FTP连接失败");
                ftpClient.disconnect();
                return false;
            }

            log.info("进入FTP服务器下载目录");
            if (!ftpClient.changeWorkingDirectory(remotePath)) {
                log.info("目录不存在");
                return false;
            }

            log.info("匹配查找文件");
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    log.info("开始下载");
                    File localFile = new File(localPath + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                    log.info("下载完成");
                } else {
                    log.info("找不到文件");
                }
            }
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            log.info("断开FTP连接");
            ftpClient.disconnect();
        }
        return true;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host         FTP服务器hostname
     * @param port         FTP服务器端口
     * @param username     FTP登录账号
     * @param password     FTP登录密码
     * @param absolutePath FTP服务器上文件的绝对路径
     * @param localPath    下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String absolutePath,
        String localPath) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            int reply;
            log.info("连接FTP服务器");
            ftpClient.connect(host, port);

            log.info("登录");
            ftpClient.login(username, password);

            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                log.info("FTP连接失败");
                ftpClient.disconnect();
                return false;
            }
            String fileName = absolutePath.substring(absolutePath.lastIndexOf('/') + 1);
            log.info("开始下载");
            File localFile = new File(localPath + "/" + fileName);
            OutputStream is = new FileOutputStream(localFile);
            ftpClient.retrieveFile(absolutePath, is);
            is.close();
            log.info("下载完成");

            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            log.info("断开FTP连接");
            ftpClient.disconnect();
        }
        return true;
    }

    public static void windowDownload(){
        InputStream in = null ;
        OutputStream out = null ;
        try {
            //创建远程文件对象
            String remotePhotoUrl = "smb://test:123456@192.168.10.125/Share/test.jpg";
            SmbFile remoteFile = new SmbFile(remotePhotoUrl);
            remoteFile.connect(); //尝试连接
            //创建文件流
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            String fileName = remoteFile.getName();
            File localFile = new File("D:/" + File.separator + fileName);
            out = new FileOutputStream(localFile);
            //读取文件内容
            byte[] buffer = new byte[1024];
            int len = 0; //读取长度

            while ((len = in.read(buffer, 0, buffer.length)) != - 1) {
                out.write(buffer, 0, len);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
            String msg = "下载远程文件出错：" + e.getLocalizedMessage();
            System.out.println(msg);
        }
        finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(in != null) {
                    in.close();
                }
            }
            catch (Exception e) {}
        }
    }

    public static void getShareFile(String remoteUrl, String savePath) {
        try {
            SmbFile smbFile = new SmbFile(remoteUrl);
            if (smbFile != null) {
                String fileName = smbFile.getName();
                File localFile = new File(savePath + File.separator + fileName);
                InputStream is = new BufferedInputStream(new SmbFileInputStream(smbFile));
                OutputStream os = new BufferedOutputStream(new FileOutputStream(localFile));
                byte[] bytes = new byte[1024];
                while (is.read(bytes) != -1) {
                    os.write(bytes);
                }
                os.flush();
                os.close();
                is.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
